package game.leon.war.game;

import com.google.protobuf.InvalidProtocolBufferException;
import game.leon.engine.net.EngineConsts;
import game.leon.engine.net.codec.GateRawMessage;
import game.leon.war.defs.MessageConsts;
import game.leon.war.defs.Vo;
import game.leon.war.gate.GateHandlerService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * User: bianpeng
 * Date: 12-1-12
 * 用户上行消息, 转发给node就可以了
 */
@Component
public class GameHandlerService {
    private Logger logger = Logger.getLogger(getClass());
    @Autowired
    private GateHandlerService gateHandlerService;
    private static int userIdSeed = 1000;
    @Autowired
    private UserSessionService userSessionService;
    public void handle(GameMessage message) {
        logger.info(String.format("message=%d", message.getMessage().getMessage()));
        if (message.getMessage().getMessage() < MessageConsts.MIN) {
            logger.info("engine message: " + message.getMessage().getMessage());
            userSessionService.del(message.getSession().getUserId());
        } else if (message.getMessage().getMessage() == MessageConsts.LOGIN) {
            assert message.getSession().getUserId() == 0;
            message.getSession().setUserId(++userIdSeed);
            // 记录到session
            userSessionService.put(message.getSession().getUserId(), message.getSession());
            try {
                byte[] data = message.getMessage().getData();
                Vo.LoginVO login = Vo.LoginVO.newBuilder().mergeFrom(data).build();
                logger.info("user login: " + login.getName());
                // 成功, 随便生成一个userID,
                // 暂时不用到数据库中去获取了
                // 给一个状态成功的VO
                message.write(MessageConsts.LOGIN, Vo.SuccessVO.newBuilder().setCode(200).build());
            } catch (InvalidProtocolBufferException e) {
                logger.error("login format error", e);
            }
        } else {
            assert message.getSession().getUserId() > 0;
            gateHandlerService.getNodeSession().getIoSession().write(
                    new GateRawMessage(message.getSession().getUserId(),
                    message.getMessage().getMessage(),
                    message.getMessage().getData()));
        }
    }
}
